﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Medianamik.UI;
using Medianamik.Core;
using Medianamik.Core.Redirect;
using System.Collections.Generic;
using Medianamik.UI.Controls;
using Medianamik.Core.Logging;

namespace Medianamik.UI.RedirectManagement
{
    public partial class _Default : BasePage 
    {
        protected string Filter
        {
            get
            {
                return ViewState["Filter"] as string ?? string.Empty;
            }
            private set
            {
                ViewState["Filter"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridRedirect.DataBind();
            }
        }


        protected void GridRedirect_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            var nodes = ConfigManager.GetAll<RedirectNode>()
                .Where(n => (n.RedirectFrom ?? string.Empty).ToLowerInvariant().Contains(Filter) &&
                    n.ParentID.Equals(MedianamikModules.RedirectManagement))
                .OrderBy(n => n.RedirectFrom);

            GridRedirect.DataSource = nodes;
        }

        protected void Filter_Filter(object sender, GridColumnFilterEventArgs e)
        {
            this.Filter = e.Value;
            GridRedirect.Rebind();
        }

        protected string FormatRedirectTo(Node pNode)
        {
            if (pNode == null)
            {
                return (string)HttpContext.GetGlobalResourceObject("Medianamik_RedirectManagement", "MissingRedirectTo");
            }

            return pNode.NodeType.LocalizedName  + " -> " + pNode.DisplayName;

        }

        protected void GridRedirect_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "delete")
            {
                Guid id = new Guid(e.CommandArgument.ToString());
                RedirectNode node = NodeManager.GetNode<RedirectNode>(id);
                if (node != null)
                {
                    var logger = new ActivityLogger();
                    logger.Log(new LoggableObject(node.RedirectFrom, LogEntryType.Redirect), "Redirect Deleted");
                }
                NodeManager.DeleteNode(id);
                RedirectDictionary.Instance.Reload();
                GridRedirect.Rebind();
            }
        }

        protected override void OnCultureChanged(CultureChangedEventArgs e)
        {
            base.OnCultureChanged(e);
            GridRedirect.Rebind();
        }
    }
}
